package com.example.emb.service.impl;

import com.example.emb.service.OutPutService;
import com.itextpdf.html2pdf.HtmlConverter;
import org.commonmark.ext.gfm.tables.TablesExtension;
import org.commonmark.node.*;
//import org.commonmark.renderer.markdown.MarkdownRenderer;
import org.commonmark.Extension;
import org.commonmark.parser.Parser;
import org.commonmark.renderer.html.HtmlRenderer;
import org.springframework.stereotype.Service;
import org.commonmark.node.*;
import org.commonmark.parser.Parser;
import org.commonmark.renderer.html.HtmlRenderer;
import java.io.*;
import java.util.Arrays;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

@Service
public class OutPutServiceImpl implements OutPutService {













    //将数据库中的String类型转化成html的markdown类型
    public static String markdownToHtml(String markdown) throws IOException {
        List<Extension> extensions = Arrays.asList(TablesExtension.create());
        Parser parser = Parser.builder()
                .extensions(extensions)
                .build();
        HtmlRenderer renderer = HtmlRenderer.builder()
                .extensions(extensions)
                .build();
        Node doc=parser.parse(markdown);
        return renderer.render(doc);
    }






    //html转换成pdf 然后打包成一个zip提供给前端下载
    private  void addPdfToZip(ZipOutputStream zip, byte[] pdfBytes, String pdfFileName) throws IOException {
        ZipEntry entry = new ZipEntry(pdfFileName);
        zip.putNextEntry(entry);
        zip.write(pdfBytes);
        zip.closeEntry();
    }

    public  byte[] convertHtmlFilesToZip(List<String> htmlFiles) {
        try (ByteArrayOutputStream zipOutputStream = new ByteArrayOutputStream();
             ZipOutputStream zip = new ZipOutputStream(zipOutputStream)) {

            for (String htmlFile : htmlFiles) {
                String pdfFileName = htmlFile.replace(".html", ".pdf"); // 根据 HTML 文件名生成 PDF 文件名
                byte[] pdfBytes = convertHtmlToPdf(htmlFile);
                if (pdfBytes != null) {
                    addPdfToZip(zip, pdfBytes, pdfFileName);
                }
            }

            zip.finish();
            System.out.println("HTML files converted to PDF and zipped successfully.");

            return zipOutputStream.toByteArray();

        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }
    private  byte[] convertHtmlToPdf(String htmlFile) {
        try (InputStream htmlInputStream = new FileInputStream(htmlFile);
             ByteArrayOutputStream pdfOutputStream = new ByteArrayOutputStream()) {

            // 使用 iText 将 HTML 转换为 PDF
            HtmlConverter.convertToPdf(htmlInputStream, pdfOutputStream);
            System.out.println("HTML converted to PDF: " + htmlFile);

            return pdfOutputStream.toByteArray();

        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }
}
